package com.dj.web.reg.controller;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.dj.core.reg.RegistService;
import com.dj.core.user.api.MobileRegistedErrorException;
import com.dj.domain.entity.DaiJiaUser;
import com.dj.web.form.tools.UserFormCopier;
import com.dj.web.utils.DaijiaWebUserUtil;

/**
 * 注册
 * 
 * @author jaen.hsu.cn@gmail.com 2012-4-19 下午1:23:24
 */
@Controller
public class RegistController {

    @Autowired
    private RegistService registService;

    /**
     * 注册首页
     * 
     * @param model
     * @return
     */
    @RequestMapping(method = RequestMethod.GET, value = "/regist")
    public String index(Model model, HttpServletRequest request) {
        // 已登录
        if (DaijiaWebUserUtil.isLogon(request)) {
            return "/reg/registed_error";
        }
        model.addAttribute(new RegUserForm());
        return "/reg/reg_index";
    }

    /**
     * 保存注册信息
     * 
     * @param regUserForm
     * @param result
     * @param request
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, value = "/regist")
    public String doRegist(@Valid RegUserForm regUserForm, BindingResult result, HttpServletRequest request) {
        // 已登录
        if (DaijiaWebUserUtil.isLogon(request)) {
            return "/reg/registed_error";
        }
        if (result.hasErrors()) {
            return "/reg/reg_index";
        }
        DaiJiaUser daijiaUser = UserFormCopier.convertRegUserForm2DaijiaUser(regUserForm, new DaiJiaUser());
        try {
            daijiaUser.setUserType(DaiJiaUser.USER_TYPE_PERSON);
            daijiaUser.setSite(DaiJiaUser.DEFAULT_USER_SITE);
            registService.registUser(daijiaUser);
            DaijiaWebUserUtil.storeUserToSession(daijiaUser, request);
        } catch (MobileRegistedErrorException e) {
            FieldError error = new FieldError("regUserForm", "mobile", "该手机号已被注册。");
            result.addError(error);
            return "/reg/reg_index";
        } catch (Exception e) {
            return "/error";
        }

        // TODO:注册成功页面，操作成功页面

        return "/index";
    }
}
